from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib.admin.views.decorators import staff_member_required

from s_te.utils import delete_slug
from cm_s.models import Page, MainPage
from cm_s.admin.forms import PageForm, MainPageForm

@staff_member_required
def main(request, template_name="cm_s/admin/main.html"):
    """
    The main page of the admin, listing all pages
    """
    pages = Page.objects.all()
    try:
        main_page = MainPage.objects.get()
    except MainPage.DoesNotExist:
        main_page = None
    if request.POST:
        form = MainPageForm(request.POST, instance=main_page)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Main page changed.")
            return HttpResponseRedirect(reverse('cm_s_admin_main'))
    else:
        form = MainPageForm(instance=main_page)
    return render_to_response(template_name, {'pages':pages, 'form':form, 'nav_page': 'cm_s_admin_main'},
                              context_instance=RequestContext(request))
    
@staff_member_required
def create(request, template_name="cm_s/admin/create.html"):
    """
    Create a new page
    """
    
    if request.POST:
        form = PageForm(request.POST)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Page created.")
            return HttpResponseRedirect(reverse('cm_s_admin_main'))
    else:
        form = PageForm()
    return render_to_response(template_name, {'form':form},
                              context_instance=RequestContext(request))
    
@staff_member_required
def edit(request, slug, template_name="cm_s/admin/edit.html"):
    """
    Edit an existing page
    """
    page = get_object_or_404(Page, slug=slug)
    if request.POST:
        form = PageForm(request.POST, instance=page)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Page saved.")
            return HttpResponseRedirect(reverse('cm_s_admin_main'))
    else:
        form = PageForm(instance=page)
    return render_to_response(template_name, {'page':page, 'form':form},
                              context_instance=RequestContext(request))

@staff_member_required
def delete(request):
    """
    Delete an existing page
    """
    delete_slug(Page, request)
    request.user.message_set.create(message="Page deleted.")
    return HttpResponseRedirect(reverse('cm_s_admin_main'))
